package com.binfast.seed.aop;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Configuration
public class GloabalAop {
    private static final Log log = LogFactory.get();

    //记录日志切面
    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void pointCutLog() {}

    @Around("pointCutLog()")
    public Object LogHandler(final ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

//        String username = request.getHeader(SecurityConstants.USER_HEADER);
//        if (StrUtil.isNotBlank(username)) {
//            log.info("Controller AOP get username:{}", username);
//            UserUtils.setUser(username);
//        }

        log.info("日志: URL          : " + request.getRequestURL().toString());
        log.info("日志: HTTP_METHOD  : " + request.getMethod());
        log.info("日志: IP           : " + request.getRemoteAddr());
        log.info("日志: CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
        log.info("日志: ARGS         : " + ArrayUtil.join(pjp.getArgs(),"--"));

        Object result;

        result = pjp.proceed();
        log.info("日志: "+pjp.getSignature() + " 用时: " + (System.currentTimeMillis() - startTime)+" ms");
//        if (StrUtil.isNotEmpty(username)) {
//            UserUtils.clearAllUserInfo();
//        }
        return result;
    }

}
